﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Mavis.Client.Common;
using MavisAzureIndexLibrary;
using MavisAzureIndexLibrary.AudioIndexingServiceRef;
using System.Threading;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Timers;
using System.Xml;

namespace MavisWPFClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private IndexClientService m_MavisAzureIndexClientService;
        System.Timers.Timer time = new System.Timers.Timer(6000);
        // Support Method
        private static void TrustAllCer()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
        }

        public MainWindow()
        {
            InitializeComponent();
            GifLoadingPic.Visibility = System.Windows.Visibility.Hidden;

        }

        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (this.WindowState != System.Windows.WindowState.Minimized)
            {
                this.WindowState = System.Windows.WindowState.Minimized;
            }
        }

        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {
            GifLoadingPic.Visibility = System.Windows.Visibility.Visible;
            Thread newThread = new Thread(new ThreadStart(LoginToMavis));
            newThread.SetApartmentState(ApartmentState.STA);
            newThread.IsBackground = true;
            newThread.Start();
        }

        private void LoginToMavis()
        {
            TrustAllCer();
            m_MavisAzureIndexClientService = MavisAzureIndexClient.GetIndexClientService();

            MavisAzureIndexClient.SignIn("mscss", "new!p4wd");
            if (MavisAzureIndexClient.IsSignedIn)
            {

                LoginStat.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                (Action)delegate() { LoginStat.Content = "Logged In"; });
                GifLoadingPic.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                (Action)delegate() { GifLoadingPic.Visibility = Visibility.Hidden; });
            }
        }

        private void ListUserBtn_Click(object sender, RoutedEventArgs e)
        {
            if (MavisAzureIndexClient.IsSignedIn)
            {
                _userCollection.Clear();
                Customer[] users = m_MavisAzureIndexClientService.ListUsers();
                foreach (Customer user in users)
                {
                    _userCollection.Add(new UserData
                    {
                        UserName = user.Name,
                        Desc = user.Description,
                    });
                }
            }
        }

        ObservableCollection<UserData> _userCollection = new ObservableCollection<UserData>();
        ObservableCollection<JobStatusData> _jobCollection = new ObservableCollection<JobStatusData>();

        public ObservableCollection<UserData> UserCollection
        {
            get
            {
                return _userCollection;
            }
        }

        public ObservableCollection<JobStatusData> JobCollection
        {
            get
            {
                return _jobCollection;
            }
        }

        public class UserData
        {
            public string UserName { get; set; }
            public string Desc { get; set; }

        }

        public class JobStatusData
        {
            public string jobid { get; set; }
            public string status { get; set; }
            public string percentage { get; set; }
            public string submittime { get; set; }
        }

        private void AddUserBtn_Click(object sender, RoutedEventArgs e)
        {
            string userName = NameTextBox.Text;
            string desc = DescTextBox.Text;
            Customer[] users = m_MavisAzureIndexClientService.ListUsers();
            int alreadyUserCount = users.Length;
            m_MavisAzureIndexClientService.AddUser(userName, desc);
            Customer[] usersNew = m_MavisAzureIndexClientService.ListUsers();
            if (usersNew.Length > alreadyUserCount)
            {
                MessageBox.Show("Add user successfully!");
            }
        }

        private void CreateBtn_Click(object sender, RoutedEventArgs e)
        {
            string mediaURL = MediaURLTextBox.Text;
            string guid = Guid.NewGuid().ToString();
            if (MavisAzureIndexClient.IsSignedIn)
            {
                m_MavisAzureIndexClientService.Submit(mediaURL, guid, "TeddyLong", "1", DateTime.Now, "MEDIA", true, true, true, false, "TeddyData", "First JOB", "This is Desc.", "mscss", "new!p4wd", "fareast");
                _jobCollection.Clear();

                Job[] jobs = m_MavisAzureIndexClientService.GetJobs(null, null, "TeddyLong");
                if (jobs != null && jobs.Length > 0)
                {
                    foreach (Job job in jobs)
                    {
                        _jobCollection.Add(new JobStatusData
                        {
                            jobid = job.JobId,
                            status = job.State.ToString(),
                            percentage = job.Percentage.ToString(),
                            submittime = job.SubmittedTime.ToString()
                        });
                    }

                }
                MessageBox.Show("Create Job Successful!");
            }
        }

        private void GetJobBtn_Click(object sender, RoutedEventArgs e)
        {
            _jobCollection.Clear();
            Job[] jobs = m_MavisAzureIndexClientService.GetJobs(null, null, "TeddyLong");
            if (jobs != null && jobs.Length > 0)
            {
                foreach (Job job in jobs)
                {
                    _jobCollection.Add(new JobStatusData
                    {
                        jobid = job.JobId,
                        status = job.State.ToString(),
                        percentage = job.Percentage,
                        submittime = job.SubmittedTime.ToString()
                    });
                }
                time.AutoReset = true;
                time.Enabled = true;
                time.Elapsed += new ElapsedEventHandler(time_Elapsed);
            }
            else
            {
                MessageBox.Show("There is no job");
            }
        }

        private void time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Job[] jobs = m_MavisAzureIndexClientService.GetJobs(null, null, "TeddyLong");
            if (jobs.Length > 0)
            {
                foreach (Job job in jobs)
                {
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate()
                    {
                        foreach (JobStatusData jobstat in _jobCollection)
                        {
                            if (jobstat.jobid == job.JobId)
                            {
                                jobstat.percentage = job.Percentage;
                                jobstat.status = job.State.ToString();
                            }
                        }
                    });
                }
            }
        }

        private void CreateRSSBtn_Click(object sender, RoutedEventArgs e)
        {
            string rssURL = "Rss.xml";

            Job[] jobs = m_MavisAzureIndexClientService.GetJobs(null, null, "TeddyLong");
            int count = jobs.Length;
            SubmitRssFile(rssURL);
            Job[] jobs1 = m_MavisAzureIndexClientService.GetJobs(null, null, "TeddyLong");

            if (jobs1.Length > count)
            {
                MessageBox.Show("Job create successful, New Job Count: " + (jobs1.Length - count));
            }
        }

        private void SubmitRssFile(string address)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(address);
            XmlNodeList itemList = doc.SelectNodes("//item");
            foreach (XmlNode item in itemList)
            {
                string mediaURL = item.SelectSingleNode("enclosure").Attributes["url"].Value;
                string guid = Guid.NewGuid().ToString();
                m_MavisAzureIndexClientService.Submit(mediaURL, guid, "TeddyLong", "2", DateTime.Now, "MEDIA", true, true, true, false, "TeddyData", "First JOB", "This is Desc.", "mscss", "new!p4wd", "fareast");
            }
        }

        private void UserList_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (_userCollection.Count > 0)
            {
                UserList.ContextMenu = UserContext;
            }
            else
            {
                UserList.ContextMenu = null;
            }
        }

        private void RemoveUserMenuItem_Click(object sender, RoutedEventArgs e)
        {
            UserData removeUser = (UserData)UserList.SelectedItem;
            m_MavisAzureIndexClientService.RemoveUser(removeUser.UserName);

            Customer[] users = m_MavisAzureIndexClientService.ListUsers();
            _userCollection.Clear();
            foreach (Customer user in users)
            {
                _userCollection.Add(new UserData
                {
                    UserName = user.Name,
                    Desc = user.Description,
                });
            }
            MessageBox.Show("Removed!");
        }

        private void JobStatusList_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (_jobCollection.Count > 0)
            {
                JobStatusList.ContextMenu = JobContext;
            }
            else
            {
                JobStatusList.ContextMenu = null;
            }
        }

        private void DownLoadCaptionMenuItem_Click(object sender, RoutedEventArgs e)
        {
            JobStatusData downloadJob = (JobStatusData)JobStatusList.SelectedItem;
            if (downloadJob.status != JobStates.Completed.ToString())
            {
                MessageBox.Show("This job is not Completed!");
            }
            else
            {
                m_MavisAzureIndexClientService.Wait("TeddyLong", downloadJob.jobid, "1", AppDomain.CurrentDomain.BaseDirectory);
                MessageBox.Show("Media Caption Downloaded!");
                _jobCollection.Clear();
                Job[] jobs = m_MavisAzureIndexClientService.GetJobs(null, null, "TeddyLong");
                if (jobs != null && jobs.Length > 0)
                {
                    foreach (Job job in jobs)
                    {
                        _jobCollection.Add(new JobStatusData
                        {
                            jobid = job.JobId,
                            status = job.State.ToString(),
                            percentage = job.Percentage,
                            submittime = job.SubmittedTime.ToString()
                        });
                    }
                }
            }
        }

        private void DeleteJobMenuItem_Click(object sender, RoutedEventArgs e)
        {
            JobStatusData deleteJob = (JobStatusData)JobStatusList.SelectedItem;
            m_MavisAzureIndexClientService.Kill("TeddyLong", deleteJob.jobid, "1");
            MessageBox.Show("Job Deleted!");
            _jobCollection.Clear();
            Job[] jobs = m_MavisAzureIndexClientService.GetJobs(null, null, "TeddyLong");
            if (jobs != null && jobs.Length > 0)
            {
                foreach (Job job in jobs)
                {
                    _jobCollection.Add(new JobStatusData
                    {
                        jobid = job.JobId,
                        status = job.State.ToString(),
                        percentage = job.Percentage,
                        submittime = job.SubmittedTime.ToString()
                    });
                }
            }
        }

        private void PreViewMenuItem_Click(object sender, RoutedEventArgs e)
        {
            MediaPlayer mp = new MediaPlayer();
            mp.Show();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MediaPlayer mp = new MediaPlayer();
            mp.Show();
        }
    }
}
